package org.tony.spider.novel.entries;

import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;

import org.tony.common.io.FileUtil;

/**
 * This is a queue which stored novel's information that will be download
 * 
 * @author tony
 *
 */
public final class NovelQueue
{
  private static final String         DATA_PATH = "novel/novel.data";
  private static final long           DELAY     = 1 * 60 * 1000;
  private static NovelQueue           instance;

  private Timer                       timer;
  private Map<String, Queue<Chapter>> novels;
  private AtomicInteger               syncFailedCount;

  private NovelQueue()
  {
    this.novels = new HashMap<String, Queue<Chapter>>();
    this.syncFailedCount = new AtomicInteger();
    this.timer = new Timer();
    timer.schedule(new TimerTask() {

      public void run()
      {
        System.out.println("start synchroinize ");
        if (syncFailedCount.get() > 30)
        {
          timer.cancel();
          throw new RuntimeException("Synchronized file failed!");
        }
        instance.sync();
      }
    }, 1000, DELAY);
  }

  public synchronized static NovelQueue getInstance()
  {
    if (instance == null)
    {
      instance = new NovelQueue();
    }
    return instance;
  }

  public synchronized void append(String bookName, Queue<Chapter> chapters)
  {
    Queue<Chapter> tempChapters = null;
    if (novels.containsKey(bookName))
    {
      tempChapters = novels.get(bookName);
      tempChapters.addAll(chapters);
    }
    else
    {
      tempChapters = chapters;
    }
    novels.remove(bookName);
    novels.put(bookName, tempChapters);
    System.out.println(chapters.size());
  }

  public synchronized Queue<Chapter> poll(String bookName)
  {
    return novels.remove(bookName);
  }

  /**
   * synchronize the data to file system
   */
  public synchronized void sync()
  {
    try
    {
      FileUtil.writeObject(DATA_PATH, novels);
      System.out.println(novels.get("狂枭").poll());
    }
    catch (Exception e)
    {
      this.syncFailedCount.incrementAndGet();
      System.out.println(e);
      //do nothing 
    }
  }
}
